from osv import osv, fields
from osv.orm import intersect
import tools.sql

class kdvn_project(osv.osv):
    _name = "kdvn.project"
    _description="KDVN Projects"

    def _delete_all_budget_line(self,cr,uid,ids,context):
        kdvn_budget_data_ids=[]
        kdvn_budget_data_obj =self.read(cr,uid,ids,['budget_data_ids'])
        if kdvn_budget_data_obj:
            kdvn_budget_data_ids =kdvn_budget_data_obj[0]['budget_data_ids'] 
        if kdvn_budget_data_ids:
            self.pool.get('kdvn.budget.data').unlink(cr,uid,kdvn_budget_data_ids,context)        
        return True
    
    def unlink(self, cr, uid, ids, context=None):
        if ids:
            prj_ids = ",".join(map(str,ids))
            if self.pool.get('kdvn.budget.data').search(cr,uid,[('project_id','in',ids)]):
                raise osv.except_osv('Warning action !','Cannot delete Project(s), You must delete all Budget related!')
            if self.pool.get('project.currency').search(cr,uid,[('project_id','in',ids)]):
                raise osv.except_osv('Warning action !','Cannot delete Project(s), You must delete all Currency related!')
            if self.pool.get('sale.order').search(cr,uid,[('project_e_id','in',ids)]) or self.pool.get('sale.order').search(cr,uid,[('project_m_id','in',ids)]):
                raise osv.except_osv('Warning action !','Cannot delete Project(s), You must delete all Quotation related!')
        unlink_ids = ids
        return super(kdvn_project, self).unlink(cr, uid, unlink_ids, context=context)
        
    def create(self, cr, uid, vals, context={}):        
        id_test=osv.osv.create(self, cr, uid, vals, context=context)
        new_id=self.pool.get('project.currency')._create_currency(cr,uid,id_test,'project',context)
        return id_test
        
    def _get_project_currency(self,cr,uid,ids,name,args,context={}):
        res={}
        if ids:
            acc_set=",".join(map(str,ids))
            cr.execute("Select project_id,id from project_currency where default_curr=True and project_id in (%s)" % acc_set)
            for ctr_id,curr_id in cr.fetchall():
                res[ctr_id]=curr_id#,'contract_rate':curr_rate}
        for id in ids:
            res[id]=res.get(id,False)
        #raise osv.except_osv("E",res)
        return res

    def _update_history(self, cr, uid, ids,context):
        for kp in self.browse(cr,uid,ids):
            self.pool.get('kdvn.budget.history').create_history(cr,uid,kp.id)
        return True
    
    def _get_quotation_lists(self, cr, uid, ids, name, arg, context=None):
        res = {}
        for id in ids:
            cr.execute('SELECT id FROM sale_order ' \
                    'WHERE project_e_id =%s or project_m_id=%s' % (id,id))
            res[id] = [x[0] for x in cr.fetchall()]
        return res
    
    def _get_direct_cost_bak(self, cr, uid, ids, name, arg, context=None):
        res = {}
        if ids:
            lst_tmp={'direct_amount_vnd':0.0,
                     'direct_amount_usd':0.0}
            for id in ids:
                res[id]=lst_tmp
            prj_id_list = ",".join(map(str,ids))
            cr.execute("select \
                            kbd.project_id,\
                            sum(budget_amount) as direct_cost_vnd,\
                            sum(case \
                                                    when rate =0\
                                                    then 0 \
                                                    else coalesce(budget_amount/rate,0) end) as direct_cost_usd\
                        from \
                            kdvn_budget_data kbd \
                        left join\
                            project_currency pc on kbd.project_id = pc.project_id and pc.name='USD'\
                        left join\
                            account_budget_post abp on kbd.budget_id=abp.id\
                        left join\
                            budget_category bc on categ_id = bc.id\
                        left join\
                            budget_category bc1 on bc.parent_id = bc1.id\
                        where \
                            bc1.cat_code='direct_cost' and kbd.project_id in (%s)\
                        group by\
                            kbd.project_id" % prj_id_list)
            for prj_id,direct_vnd,direct_usd in cr.fetchall():
                res[prj_id]['direct_amount_vnd']=direct_vnd
                res[prj_id]['direct_amount_usd']=direct_usd
        return res
    
    def _get_direct_cost_usd(self, cr, uid, ids, name, arg, context=None):
        res = {}
        if ids:
            prj_id_list = ",".join(map(str,ids))
            cr.execute("select \
                            kp.id,\
                            sum(case \
                                when rate =0\
                                then 0 \
                                else coalesce(budget_amount/rate,0) end) as direct_cost_usd\
                        from\
                            kdvn_project kp\
                        left join\
                            kdvn_budget_data kbd on kp.id = kbd.project_id\
                        left join\
                            project_currency pc on kp.id = pc.project_id and pc.name='USD'\
                        left join\
                            account_budget_post abp on kbd.budget_id=abp.id\
                        left join\
                            budget_category bc on categ_id = bc.id\
                        left join\
                            budget_category bc1 on bc.parent_id = bc1.id\
                        where \
                            bc1.cat_code='direct_cost' and kbd.project_id in (%s)\
                        group by\
                            kp.id" % prj_id_list)
            for prj_id,direct_usd in cr.fetchall():
                res[prj_id] = direct_usd
        return res
      
    def name_get(self, cr, uid, ids, context={}):
        if not len(ids):
            return []
        res = []
        reads = self.read(cr, uid, ids, ['name','code'], context)
        code_only = False
        if 'code_only' in context:
            code_only = context['code_only']
                
        for record in reads:
            name=''
            if record:
                if code_only:
                    name = record['code']
                else:
                    name = record['code']+" - "+record['name']
                res.append((record['id'], name))        
        return res
    
    def _get_project_cost_info(self, cr, uid, ids, name, args, context=None):
        res = {}
        if ids:
            project_info_lists={
                                'project_budget_total_vnd':0.0,'project_budget_total_usd':0.0,
                                'expense_vnd':0.0,'expense_usd':0.0,
                                'payment_vnd':0.0,'payment_usd':0.0}#'project_amount_vnd':0.0,'project_vat_vnd':0.0,'project_total_vnd':0.0,
#Claim and Received Amount in VND
                                #'contract_amount': 0.0,'contract_vat': 0.0,'contract_total': 0.0,
#                                'prj_claim_amount_vnd': 0.0,'prj_claim_amount_usd': 0.0,
#                                'prj_recv_amount_vnd': 0.0, 'prj_recv_amount_usd': 0.0,
                                
            for id in ids:
                res[id]=project_info_lists
            prj_id_list = ",".join(map(str, ids))
            
#            \
#            coalesce((case when coalesce(pc_vnd.rate,0)=0 then 0 else project_amount*pc.rate/pc_vnd.rate end),0) as project_amount_vnd,\
#            coalesce((case when coalesce(pc_vnd.rate,0)=0 then 0 else project_vat*pc.rate/pc_vnd.rate end),0) as project_vat_vnd,\
#            coalesce((case when coalesce(pc_vnd.rate,0)=0 then 0 else project_total*pc.rate/pc_vnd.rate end),0) as project_total_vnd,\
            
#             \coalesce((case when coalesce(pc_usd.rate,0)=0 then 0 else project_amount*pc.rate/pc_usd.rate end),0) as project_amount_usd,\
#            coalesce((case when coalesce(pc_usd.rate,0)=0 then 0 else project_vat*pc.rate/pc_usd.rate end),0) as project_vat_usd,\
#            coalesce((case when coalesce(pc_usd.rate,0)=0 then 0 else project_total*pc.rate/pc_usd.rate end),0) as project_total_usd,\
            cr.execute("Select \
                            kp.id,\
                            \
                            coalesce(sum(budget_amount),0) as project_budget_total_vnd,\
                            coalesce(sum(case when coalesce(pc_usd.rate,0)=0 then 0 else budget_amount/pc_usd.rate end),0) as project_budget_total_usd,\
                            \
                            (coalesce(subtotalvnd,0)) as expense_vnd,\
                            (coalesce(subtotalusd,0)) as expense_usd,\
                            (coalesce(payment_vnd,0)) as payment_vnd,\
                            (coalesce(payment_usd,0)) as payment_usd \
                        from \
                            kdvn_project kp\
                        left join\
                            project_currency pc_usd on kp.id=pc_usd.project_id and pc_usd.name='USD'\
                        left join\
                            kdvn_budget_data kbd on kp.id = kbd.project_id\
                        left join\
                            (Select\
                                            pol.project_id,\
                                            coalesce(sum(price_subtotal2*rate*fnpo_compute(fnpo_currnametoid('VND'),po.currency_id,date_order)),0) as subtotalvnd,\
                                            coalesce(sum(price_subtotal2*fnpo_compute(fnpo_currnametoid('USD'),po.currency_id,date_order)),0) as subtotalusd,\
                                            coalesce(payment_vnd,0) as payment_vnd,\
                                            coalesce(payment_usd,0) as payment_usd\
                                        from \
                                            purchase_order po\
                                        left join \
                                            purchase_order_line pol on po.id=order_id\
                                        left join \
                                            vwpo_rate vwr on po.id=vwr.id\
                                        left join\
                                            (Select \
                                kropd.project_id,\
                                sum(coalesce(kropd.amount,0)*rate*coalesce(fnpo_compute(fnpo_currnametoid('VND'),po.currency_id,date_order),0)) as payment_vnd,\
                                sum(coalesce(kropd.amount,0)*coalesce(fnpo_compute(fnpo_currnametoid('USD'),po.currency_id,date_order),0)) as payment_usd\
                                            from\
                                kdvn_request_of_payment krop\
                            left join\
                                kdvn_request_of_payment_detail kropd on krop.id=kropd.rop_id\
                            left join\
                                purchase_order po on order_id = po.id\
                            left join \
                                vwpo_rate vwr on po.id=vwr.id\
                            where krop.state not in ('draft','cancel')\
                            group by kropd.project_id) vwtemp on pol.project_id=vwtemp.project_id\
                                        where\
                                            po.state not in ('cancel','draft')\
                                        group by\
                                            pol.project_id,payment_vnd,payment_usd) vwexpense on kp.id=vwexpense.project_id\
                        where \
                            kp.id in (%s)\
                        group by kp.id,\
                            pc_usd.rate,\
                            expense_vnd,expense_usd,\
                            payment_vnd,payment_usd" % (prj_id_list))
        for prj_list in cr.dictfetchall():
            tmp_id=prj_list.pop('id')
            res[tmp_id].update(prj_list)
        return res
    
    def _get_project_cost_info_bak(self, cr, uid, ids, name, args, context=None):
        res = {}
        if ids:
            project_info_lists={'project_amount_vnd':0.0,'project_vat_vnd':0.0,'project_total_vnd':0.0,
                                'project_amount_usd':0.0,'project_vat_usd':0.0,'project_total_usd':0.0,
                                'project_budget_total_vnd':0.0,'project_budget_total_usd':0.0,
#Claim and Received Amount in VND
                                #'contract_amount': 0.0,'contract_vat': 0.0,'contract_total': 0.0,
#                                'prj_claim_amount_vnd': 0.0,'prj_claim_amount_usd': 0.0,
#                                'prj_recv_amount_vnd': 0.0, 'prj_recv_amount_usd': 0.0,
                                'expense_vnd':0.0,'expense_usd':0.0,
                                'payment_vnd':0.0,'payment_usd':0.0}
            for id in ids:
                res[id]=project_info_lists
            prj_id_list = ",".join(map(str, ids))
            
            cr.execute("Select \
                            kp.id,\
                            \
                            coalesce(sum(budget_amount),0) as project_budget_total_vnd,\
                            coalesce(sum(case when coalesce(pc_usd.rate,0)=0 then 0 else budget_amount/pc_usd.rate end),0) as project_budget_total_usd,\
                            \
                            coalesce((case when coalesce(pc_vnd.rate,0)=0 then 0 else project_amount*pc.rate/pc_vnd.rate end),0) as project_amount_vnd,\
                            coalesce((case when coalesce(pc_vnd.rate,0)=0 then 0 else project_vat*pc.rate/pc_vnd.rate end),0) as project_vat_vnd,\
                            coalesce((case when coalesce(pc_vnd.rate,0)=0 then 0 else project_total*pc.rate/pc_vnd.rate end),0) as project_total_vnd,\
                            \
                            coalesce((case when coalesce(pc_usd.rate,0)=0 then 0 else project_amount*pc.rate/pc_usd.rate end),0) as project_amount_usd,\
                            coalesce((case when coalesce(pc_usd.rate,0)=0 then 0 else project_vat*pc.rate/pc_usd.rate end),0) as project_vat_usd,\
                            coalesce((case when coalesce(pc_usd.rate,0)=0 then 0 else project_total*pc.rate/pc_usd.rate end),0) as project_total_usd,\
                            \
                            (coalesce(subtotalvnd,0)) as expense_vnd,\
                            (coalesce(subtotalusd,0)) as expense_usd,\
                            (coalesce(payment_vnd,0)) as payment_vnd,\
                            (coalesce(payment_usd,0)) as payment_usd \
                        from \
                            kdvn_project kp\
                        left join\
                            project_currency pc on kp.id = pc.project_id and default_curr=True\
                        left join\
                            project_currency pc_usd on kp.id=pc_usd.project_id and pc_usd.name='USD'\
                        left join\
                            project_currency pc_vnd on  kp.id=pc_vnd.project_id and pc_vnd.name='VND'\
                        left join\
                            kdvn_budget_data kbd on kp.id = kbd.project_id\
                        left join\
                            (Select\
                                pol.project_id,\
                                coalesce(sum(price_subtotal2*rate*fnpo_compute(fnpo_currnametoid('VND'),po.currency_id,date_order)),0) as subtotalvnd,\
                                coalesce(sum(price_subtotal2*fnpo_compute(fnpo_currnametoid('USD'),po.currency_id,date_order)),0) as subtotalusd,\
                                sum(coalesce(kropd.amount,0)*coalesce(rate,1)*coalesce(fnpo_compute(fnpo_currnametoid('VND'),krop.currency_id,date_order),0)) as payment_vnd,\
                                sum(coalesce(kropd.amount,0)*coalesce(fnpo_compute(fnpo_currnametoid('USD'),krop.currency_id,date_order),0)) as payment_usd\
                            from \
                                purchase_order po\
                            left join \
                                purchase_order_line pol on po.id=order_id\
                            left join \
                                vwpo_rate vwr on po.id=vwr.id\
                            left join\
                                kdvn_request_of_payment krop on po.id=krop.order_id and krop.state<>'draft' and krop.state<>'cancel'\
                            left join\
                                kdvn_request_of_payment_detail kropd on krop.id=kropd.rop_id\
                            left join \
                                (Select distinct\
                                    payment_id\
                                from\
                                    kdvn_payment) kp on krop.id=payment_id and kp.payment_id>0\
                            where\
                                po.state not in ('cancel','draft')\
                            group by\
                                pol.project_id) vwexpense on kp.id=vwexpense.project_id\
                        where \
                            kp.id in (%s)\
                        group by kp.id,\
                            pc_vnd.rate,project_amount,\
                            project_vat,project_total,\
                            pc_usd.rate,pc.rate,\
                            expense_vnd,expense_usd,\
                            payment_vnd,payment_usd" % (prj_id_list))
        for prj_list in cr.dictfetchall():
            tmp_id=prj_list.pop('id')
            res[tmp_id].update(prj_list)
        return res
    
    def _get_project_cost_claim_recv_info(self, cr, uid, ids, name, args, context=None):
        res = {}
        if ids:
            project_info_cost_claim_lists={'prj_claim_amount_vnd': 0.0,'prj_claim_amount_usd': 0.0,
                                'prj_recv_amount_vnd': 0.0, 'prj_recv_amount_usd': 0.0,
                                'project_amount_vnd':0.0,'project_vat_vnd':0.0,'project_total_vnd':0.0,
                                'project_amount_usd':0.0,'project_vat_usd':0.0,'project_total_usd':0.0}
            for id in ids:
                res[id]=project_info_cost_claim_lists
            prj_id_list = ",".join(map(str, ids))
            
            cr.execute("Select \
                            project_id as id,\
                            case when\
                                project_type='E'\
                            then\
                                sum(contract_claim_vnd*prj_e_percent)\
                            else\
                                sum(contract_claim_vnd*prj_m_percent)\
                            end as prj_claim_amount_vnd,\
                            \
                            case when\
                                project_type='E'\
                            then\
                                sum(contract_claim_usd*prj_e_percent)\
                            else\
                                sum(contract_claim_usd*prj_m_percent)\
                            end as prj_claim_amount_usd,\
                            \
                            case when \
                                project_type='E' \
                            then    \
                                sum(contract_recv_vnd*prj_e_percent)\
                            else\
                                sum(contract_recv_vnd*prj_m_percent)\
                            end as prj_recv_amount_vnd,\
                        \
                            case when \
                                project_type='E' \
                            then    \
                                sum(contract_recv_usd*prj_e_percent)\
                            else\
                                sum(contract_recv_usd*prj_m_percent)\
                            end as prj_recv_amount_usd,\
                            \
                            case when \
                                project_type='E' \
                            then    \
                                sum(contract_amount_vnd*prj_e_percent)\
                            else\
                                sum(contract_amount_vnd*prj_m_percent)\
                            end as project_amount_vnd,\
                            case when \
                                project_type='E' \
                            then    \
                                sum(tax_per*contract_amount_vnd*prj_e_percent)\
                            else\
                                sum(tax_per*contract_amount_vnd*prj_m_percent)\
                            end/100 as project_vat_vnd,\
                            case when \
                                project_type='E' \
                            then    \
                                sum((1+tax_per/100.0)*contract_amount_vnd*prj_e_percent)\
                            else\
                                sum((1+tax_per/100.0)*contract_amount_vnd*prj_m_percent)\
                            end as project_total_vnd,\
                            \
                            case when \
                                project_type='E' \
                            then    \
                                sum(contract_amount_usd*prj_e_percent)\
                            else\
                                sum(contract_amount_usd*prj_m_percent)\
                            end as project_amount_usd,\
                            case when \
                                project_type='E' \
                            then    \
                                sum(tax_per*contract_amount_usd*prj_e_percent)\
                            else\
                                sum(tax_per*contract_amount_usd*prj_m_percent)\
                            end/100 as project_vat_usd,\
                            case when \
                                project_type='E' \
                            then    \
                                sum((1 + tax_per/100.0)*contract_amount_usd*prj_e_percent)\
                            else\
                                sum((1 + tax_per/100.0)*contract_amount_usd*prj_m_percent)\
                            end as project_total_usd\
                        \
                        from \
                            kdvn_project_contract_rel kpcr\
                        left join\
                            (Select \
                                kcc.id,\
                                case when \
                                    (coalesce(contract_amount_e,0)+coalesce(contract_amount_m,0))=0 \
                                then \
                                    0 \
                                else\
                                    coalesce(contract_amount_e,0)/(coalesce(contract_amount_e,0)+coalesce(contract_amount_m,0)) end as prj_e_percent,\
                                case when \
                                    (coalesce(contract_amount_e,0)+coalesce(contract_amount_m,0))=0 \
                                then \
                                    0 \
                                else\
                                    coalesce(contract_amount_m,0)/(coalesce(contract_amount_e,0)+coalesce(contract_amount_m,0)) end as prj_m_percent,\
                                claim_amount_usd as contract_claim_usd,\
                                claim_amount_vnd  as contract_claim_vnd,\
                                received_usd as contract_recv_usd,\
                                received_vnd as contract_recv_vnd,\
                                contract_amount_vnd,\
                                contract_amount_usd,\
                                case when coalesce(contract_total-contract_vat,0)=0 then 0 else  contract_vat/(contract_total-contract_vat)*100 end as tax_per\
                            from \
                                kdvn_contract_client kcc\
                            left join\
                                (Select \
                                    vwtemp.id,\
                                    claim_amount_usd,\
                                    claim_amount_vnd,\
                                    received_usd,\
                                    received_vnd,\
                                    contract_amount_vnd,\
                                    contract_amount_usd\
                                from \
                                    (Select\
                                    id,                                \
                                    sum(contract_amount_usd) as contract_amount_usd,\
                                    sum(contract_amount_vnd) as contract_amount_vnd,\
                                    sum(claim_amount_vnd) as claim_amount_vnd,\
                                    sum(claim_amount_usd) as claim_amount_usd,\
                                    sum(received_usd) as received_usd,\
                                    sum(received_vnd) as received_vnd,\
                                    case when sum(plan_cost_vnd+plan_vat_vnd) is null or sum(plan_cost_vnd+plan_vat_vnd)=0 then 1 else \
                                    sum(contract_amount_vnd + contract_vat_vnd)/sum(plan_cost_vnd+plan_vat_vnd) end as received_rate\
                                    from vwproject_contract_received_summary \
                                    group by id) vwtemp) vwcr\
                            on kcc.id=vwcr.id) vwtemp on contract_id=id\
                        left join\
                            kdvn_project kp on project_id=kp.id\
                        where project_id in (%s)\
                        group by project_id,project_type" % (prj_id_list))
        for prj_list in cr.dictfetchall():
            tmp_id=prj_list.pop('id')
            res[tmp_id].update(prj_list)
        return res
    
    def _get_contract_lists(self, cr, uid, ids, name, arg, context=None):
        res={}
        for id in ids:
            cr.execute("Select distinct contract_id from sale_order where coalesce(contract_id,0)>0 and not state in ('draft','cancel') and (project_e_id = %s or project_m_id = %s)" %(id,id))
            res[id] = [x[0] for x in cr.fetchall()]
        return res
    
    def _get_check_over(self, cr, uid, ids, name, arg, context=None):
        res ={}
        if ids:
            prj_ids = ",".join(map(str,ids))
            cr.execute('Select Distinct\
                            kp.id,\
                            (coalesce(krpbs.over,False)) as overed\
                        from\
                            kdvn_project kp\
                        left join\
                            kdvn_report_project_budget_status krpbs on kp.id = project_id and krpbs.over<>False\
                        group by kp.id,overed')
            for prj_id,over in cr.fetchall():
                res[prj_id] = over 
        return res

    def _newcode_suggest(self,cr,uid,context={}):
        list_newcode = []
        cr.execute("Select \
                        * \
                    from\
                        (Select * from vwnew_electrical_project_code\
                        union\
                        Select * from vwnew_mechanical_project_code) vwtemp\
                    order by newcode")
        #list_newcode=''
        for ncode,nname in cr.fetchall(): 
            list_newcode.append((ncode,ncode +": " + nname))
            
        return list_newcode
    
    def _onchange_suggest_code(self, cr, uid, ids,new_code):
        if new_code:
            val={'value':{'code':new_code,'newcode_suggest':False}}
        else:
            val={}
        return val
    
    _columns ={
                'code':fields.char('Job Code',size=30,required=1,select=1),
                'newcode_suggest':fields.selection(_newcode_suggest,'New Code',size=16,store=False),
                'name':fields.char('Project Name',size=256,required=1,select=1),
                
                'registration_date':fields.date("Reg. Date",select=2),
                'started_date':fields.date('Started Date',select=2),
                'completion_date':fields.date('Completion Date',select=2),
                'closed_date':fields.date('Closed Date',select=2),
                                
                'project_type':fields.selection([('E','Electrical'),('M','Mechanical')],"Project Type",select=1,required=True),
                'project_status':fields.selection([('doing','On-Going'),('done','Completed'),('closed','Closed'),('cancel','Canceled')],"Prj. Status"),
                
                'description':fields.text("Description"),
                
                'project_manager_id':fields.many2one("res.users",'Prj. Manager'),
                'site_manager_id':fields.many2one('res.users','Site Manager'),
                #'contract_id':fields.many2one('kdvn.contract.client','Contract',select=1),
                #'contract_ids':fields.many2many('kdvn.contract.client','kdvn_project_contract_rel','project_id','contract_id','Contracts'),
                
                'budget_data_ids':fields.one2many('kdvn.budget.data','project_id','Budget Lines'),
                'budget_history_ids':fields.one2many('kdvn.budget.history','project_id','Budget History'),
                
                'contract_ids':fields.function(_get_contract_lists,relation='kdvn.contract.client',type='one2many',string='Contracts',method=True),
                'quotation_lists':fields.function(_get_quotation_lists,relation='sale.order',type='one2many',string='Quotations List',method=True),
                
                'owner_id':fields.many2one('res.partner','Owner'),
                'client_id':fields.many2one('res.partner','Client'),
                'address_id':fields.many2one('res.partner.address','Address'),
                'invoice_address_id':fields.many2one('res.partner.address','Invoice Address'),
                
                'project_currency_ids':fields.one2many('project.currency','project_id','Project Currencies'),
                'project_currency_reference':fields.function(_get_project_currency,
                                                    type='many2one',
                                                    relation="project.currency",
                                                    string="Cur.",
                                                    readonly=True,
                                                    method=True,
                                                    store=True,
                                                    help='Use below Currency System to update'),
                                                    
                'project_exrate_reference':fields.float('Ex.Rate',readonly=True),
                'project_amount':fields.float('Amount',readonly=True),
                'project_vat':fields.float('V.A.T.',readonly=True),
                'project_total':fields.float('Total',readonly=True),
                
                #Project Cost Info VND & USD
                    #Contract Info
                #'exrate_usd':fields.function(_get_project_cost_info,string='Ref. Ex.Rate',type='float',method=True,multi='project_cost_info'),
#                'contract_amount':fields.function(_get_project_cost_info,string='Contract Amt.',type='float',method=True,multi='project_cost_info'),
#                'contract_vat':fields.function(_get_project_cost_info,string='Contract V.A.T',type='float',method=True,multi='project_cost_info'),
#                'contract_total':fields.function(_get_project_cost_info,string='Contract Total',type='float',method=True,multi='project_cost_info'),
                
                'project_amount_vnd':fields.function(_get_project_cost_claim_recv_info,string='Amount in VND',type='float',method=True,multi='project_cost_cr_info'),
                'project_vat_vnd':fields.function(_get_project_cost_claim_recv_info,string='VAT in VND',type='float',method=True,multi='project_cost_cr_info'),
                'project_total_vnd':fields.function(_get_project_cost_claim_recv_info,string='Total in VND',type='float',method=True,multi='project_cost_cr_info'),
                
                'project_amount_usd':fields.function(_get_project_cost_claim_recv_info,string='Amount in USD',type='float',method=True,multi='project_cost_cr_info'),
                'project_vat_usd':fields.function(_get_project_cost_claim_recv_info,string='VAT in USD',type='float',method=True,multi='project_cost_cr_info'),
                'project_total_usd':fields.function(_get_project_cost_claim_recv_info,string='Total in USD',type='float',method=True,multi='project_cost_cr_info'),
                
                'project_budget_total_vnd':fields.function(_get_project_cost_info,string='Project Budget in VND',type='float',method=True,multi='project_cost_info'),
                'project_budget_total_usd':fields.function(_get_project_cost_info,string='Project Budget in USD',type='float',method=True,multi='project_cost_info'),
                
                #'direct_amount_vnd':fields.function(_get_direct_cost,string='Direct In VND',type='float',method=True,multi='direct_cost'),,multi='direct_cost'
                'direct_amount_usd':fields.function(_get_direct_cost_usd,string='Direct In USD',type='float',method=True),
                
                'expense_vnd':fields.function(_get_project_cost_info,string='Expense VND',type='float',method=True,multi='project_cost_info'),
                'expense_usd':fields.function(_get_project_cost_info,string='Expense USD',type='float',method=True,multi='project_cost_info'),
                
                'payment_vnd':fields.function(_get_project_cost_info,string='Payment VND',type='float',method=True,multi='project_cost_info'),
                'payment_usd':fields.function(_get_project_cost_info,string='Payment USD',type='float',method=True,multi='project_cost_info'),
                
                'prj_claim_amount_vnd':fields.function(_get_project_cost_claim_recv_info,string='Claim in VND',type='float',method=True,multi='project_cost_cr_info'),
                'prj_claim_amount_usd':fields.function(_get_project_cost_claim_recv_info,string='Claim in USD',type='float',method=True,multi='project_cost_cr_info'),
                
                'prj_recv_amount_vnd':fields.function(_get_project_cost_claim_recv_info,string='Recv. in VND',type='float',method=True,multi='project_cost_cr_info'),
                'prj_recv_amount_usd':fields.function(_get_project_cost_claim_recv_info,string='Recv. in USD',type='float',method=True,multi='project_cost_cr_info'),
                
                'check_over':fields.function(_get_check_over,string='Over',type='boolean',method=True) #Project is overred budget is True else False
                } 
    _sql_constraints = [('code_unique_project', 'unique (code)', 'KDVN Error: The code of the project must be unique !')] 
    _defaults = {  
        'project_type':lambda *x:"E",
        'project_status':lambda *x:"doing",
        'project_vat':lambda *x:0.0,
        'project_total':lambda *x:0.0,
        'project_exrate_reference':lambda *x:0.0,
        }
    
    def _onchange_client_id(self, cr, uid, ids, partner_id):
        invoice_addr_id = False
        address_id = False
        if partner_id:
            res = self.pool.get('res.partner').address_get(cr, uid, [partner_id], ['default', 'invoice'])
            invoice_addr_id = res['invoice']
            address_id = False
            if res['default']:
                address_id = res['default'] 
            if not invoice_addr_id and address_id:  
                invoice_addr_id =address_id
                
        result = {'value': {'invoice_address_id': invoice_addr_id,
                            'address_id':address_id}}
        return result    
kdvn_project()